﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HouseOfCards
{
   /// <summary>
   /// Exception occurs when getting next card from an empty deck
   /// </summary>
   public class DeckEmptyException : SystemException
   {
      /// <summary>
      /// Creates a deck empty exception
      /// </summary>
      public DeckEmptyException()
      {
      }

      /// <summary>
      /// Creates a deck empty exception
      /// </summary>
      /// <param name="message"></param>
      public DeckEmptyException(string message)
         : base(message)
      {
      }

   }

   /// <summary>
   /// Object that represents a deck of cards
   /// </summary>
   public class Deck
   {
      private Stack<byte> _deck = new Stack<byte>();

      /// <summary>
      /// Creates a new deck of cards
      /// </summary>
      public Deck()
      {
         _deck = new Stack<byte>(); // card stack
      }

      /// <summary>
      /// Returns the number of cards in the deck
      /// </summary>
      public int Count
      {
         get
         {
            return _deck.Count;
         }
      }

      /// <summary>
      /// Clears the deck
      /// </summary>
      public void Clear()
      {
         _deck.Clear();
      }


      /// <summary>
      /// Returns the next card in the deck
      /// </summary>
      public Card GetNextCard()
      {
         byte nextCard;

         try
         {
            nextCard = _deck.Pop();
            return new Card(nextCard);
         }
         catch (Exception /*ex*/)
         {
            throw new DeckEmptyException("No more cards in deck");
         }
      }

      /// <summary>
      /// Shuffles the deck of cards
      /// </summary>
      public void Shuffle()
      {
         byte card;
         Random rnd = new Random();
         //populate the card deck
         if (_deck.Count > 0)
         {
            _deck.Clear();
         }

         //populate the card stack
         if (_deck.Count > 0)
         {
            _deck.Clear();
         }
         card = System.Convert.ToByte(rnd.Next(0, 52));
         do
         {
            while (_deck.Contains(card))
            {
               card = System.Convert.ToByte(rnd.Next(0, 52));
            }
            _deck.Push(card);
         } while (_deck.Count < 52);
      }

   }
}
